package leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 描述:102. 二叉树的层序遍历
 *
 * @author Madison You
 * @created 22:57
 */
public class Mid_102_LevelOrder {

    public static void main(String[] args) {
//        TreeNode treeNode1 = new TreeNode(3, null, null);
//        TreeNode treeNode2 = new TreeNode(4, null, null);
        TreeNode treeNode3 = new TreeNode(15, null, null);
        TreeNode treeNode4 = new TreeNode(7, null, null);
        TreeNode treeNode5 = new TreeNode(9, null, null);
        TreeNode treeNode6 = new TreeNode(20, treeNode3, treeNode4);
        TreeNode treeNode = new TreeNode(3, treeNode5, treeNode6);
        new Mid_102_LevelOrder().levelOrder(treeNode);
    }

    List<List<Integer>> list = new ArrayList<List<Integer>>();

    Queue<TreeNode> queue = new LinkedBlockingQueue<>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return list;
        }
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<Integer>();
            int currentLevelSize = queue.size();
            for (int i = 1; i <= currentLevelSize; ++i) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            list.add(level);
        }
        return list;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
